Public Class AdjustQuantity
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents lblCustomerName As System.Web.UI.WebControls.Label
    Protected WithEvents lblOrderNo As System.Web.UI.WebControls.Label
    Protected WithEvents btnOK As System.Web.UI.WebControls.Button
    Protected WithEvents btnCancel As System.Web.UI.WebControls.Button
    Protected WithEvents txtAdjBy As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator2 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents hidAdjBy As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents txtAdjDate As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator3 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtAdjApprovedBy As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator4 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents hidAdjApprovedBy As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents txtApprovalDate As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator5 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents btnReset As System.Web.UI.WebControls.Button
    Protected WithEvents hidCustomerID As System.Web.UI.HtmlControls.HtmlInputHidden
    Protected WithEvents repProInfo As System.Web.UI.WebControls.Repeater

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Protected WithEvents Header1 As Header

    Private Const REMIND_TEXT As String = "Remember to save before switching to another product"
    Private Const SAVE_SUCCESS_TEXT As String = "Product updated successful"
    Private Const ORDER_LIST_URL As String = "/Internal/OrderList.aspx"

#Region "   Properties"
    Private ReadOnly Property ReturnURL() As String
        Get
            If IsNothing(Request.QueryString("ru")) Then
                Return AppRoot() & Me.ORDER_LIST_URL
            End If
            Return Server.UrlDecode(Request.QueryString("ru"))
        End Get
    End Property

    Protected Property PageBO() As COrder
        Get
            If IsNothing(Session(OrderInput.ORDER_INPUT_PAGEBO_SESSION_NAME)) Then
                Throw New ApplicationException("Session expried. Please re-login")
            End If
            Return CType(Session(OrderInput.ORDER_INPUT_PAGEBO_SESSION_NAME), COrder)
        End Get
        Set(ByVal Value As COrder)
            Session(OrderInput.ORDER_INPUT_PAGEBO_SESSION_NAME) = Value
        End Set
    End Property

    Private Property Url() As String
        Get
            Return CStr(ViewState("Url"))
        End Get
        Set(ByVal Value As String)
            ViewState("Url") = Value
        End Set
    End Property

    Private Property UrlReferrer() As String
        Get
            Return CStr(ViewState("UrlReferrer"))
        End Get
        Set(ByVal Value As String)
            ViewState("UrlReferrer") = Value
        End Set
    End Property

    Private Property PreviousOIIndex() As Integer
        Get
            Return CInt(ViewState("PreviousOIIndex"))
        End Get
        Set(ByVal Value As Integer)
            ViewState("PreviousOIIndex") = Value
        End Set
    End Property

    Protected ReadOnly Property OrderID() As Integer
        Get
            Try
                If IsNothing(Request.QueryString("id")) Then
                    Throw New Exception
                End If

                Dim id As Integer
                id = CInt(Request.QueryString("id"))

                If Not id > 0 Then
                    Throw New Exception
                End If

                Return id
            Catch ex As Exception
                Throw New ApplicationException("Invalid or missing parameter", ex)
            End Try
        End Get
    End Property
#End Region


    Private Sub UpdateData(ByVal bSave As Boolean)

        With PageBO

            If bSave Then

                .AdjustedDate = CDate(Me.txtAdjDate.Text)
                .AdjustedByID = CInt(Me.hidAdjBy.Value)
                .AdjustedApprovedDate = CDate(Me.txtApprovalDate.Text)
                .AdjustedApprovedByID = CInt(Me.hidAdjApprovedBy.Value)

                'Order Item Quantites
                Dim i As Integer
                For i = 0 To Me.repProInfo.Items.Count - 1
                    Dim txtQuan As TextBox = CType(repProInfo.Items(i).FindControl("txtQuantity"), TextBox)
                    Dim hidOrderItemIndex As HtmlInputHidden = CType(repProInfo.Items(i).FindControl("hidOrderItemIndex"), HtmlInputHidden)

                    If (txtQuan.Text.Trim() <> "") Then
                        .OrderItem(CInt(hidOrderItemIndex.Value)).AdjustedQuantity = CInt(txtQuan.Text)
                    Else
                        ' set null
                        .OrderItem(CInt(hidOrderItemIndex.Value)).AdjustedQuantity = 0
                    End If

                Next

            Else

                Me.hidAdjApprovedBy.Value = .AdjustedApprovedByID.ToString
                Me.txtAdjApprovedBy.Text = CCustomerContact.GetContactName(.AdjustedApprovedByID)

                'default value for "adjust by" is current user
                If .AdjustedByID > 0 Then
                    Me.hidAdjBy.Value = .AdjustedByID.ToString
                    Me.txtAdjBy.Text = CUser.GetName(.AdjustedByID)
                Else
                    Me.hidAdjBy.Value = Security.GetCurrentUser.UsIdPk.ToString
                    Me.txtAdjBy.Text = Security.GetCurrentUser.Name
                End If

                ' adjusted date, default value is today
                If .AdjustedDate > Now.MinValue Then
                    Me.txtAdjDate.Text = FormatDate(.AdjustedDate)
                Else
                    Me.txtAdjDate.Text = FormatDate(Now.Date)
                End If

                ' approval date, default value is nothing
                If .AdjustedApprovedDate > Now.MinValue Then
                    Me.txtApprovalDate.Text = FormatDate(.AdjustedApprovedDate)
                Else
                    Me.txtApprovalDate.Text = Nothing
                End If


                ' Serialize all adjustable Products
                Dim dt As New DataTable
                dt.Columns.Add("OrderItemID")
                dt.Columns.Add("ProductInfo")
                dt.Columns.Add("Packing")
                dt.Columns.Add("Quantity")
                dt.Columns.Add("OrderItemIndex")
                dt.Columns.Add("AdjustQuantity")
                Dim i As Integer
                For i = 0 To PageBO.OrderItems.Count - 1
                    If Not PageBO.OrderItem(i).IsFixed Then
                        Dim row As DataRow = dt.NewRow
                        row(0) = PageBO.OrderItem(i).ID
                        row(1) = String.Format("{0}-{1}-{2}", PageBO.OrderItem(i).ProductCode, PageBO.OrderItem(i).ProductDescription, PageBO.OrderItem(i).Color)
                        row(2) = PageBO.OrderItem(i).Packing
                        row(3) = PageBO.OrderItem(i).Quantity
                        row(4) = i.ToString()
                        row(5) = IIf(PageBO.OrderItem(i).AdjustedQuantity > 0, PageBO.OrderItem(i).AdjustedQuantity, "")
                        dt.Rows.Add(row)
                    End If
                Next

                Me.repProInfo.DataSource = dt
                Me.repProInfo.DataBind()

            End If
        End With
    End Sub

    Private Sub PreConditionCheck()
        '"...is only enabled if BO or PO quantity is not fixed and order status is Active..."
        'from uc_SystemOrderListPage
        If PageBO.IsAllQuantityFixed Or PageBO.Status <> EOrderStatus.Active Then
            Throw New ApplicationException("You can not adjust quantity for this order")
        End If
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If Not Page.IsPostBack Then
            Security.InternalAndAdminOnly()

            Dim obj As New COrder

            Try
                obj.Load(Me.OrderID)
                PageBO = obj
            Catch ex As Exception
                Throw New ApplicationException("Failed to load order data", ex)
            End Try

            PreConditionCheck()

            Me.Url = Request.Url.PathAndQuery
            Me.UrlReferrer = Request.UrlReferrer.PathAndQuery

            Me.lblCustomerName.Text = CUser.GetName(PageBO.CustomerID)
            Me.hidCustomerID.Value = PageBO.CustomerID.ToString
            Me.lblOrderNo.Text = PageBO.OrderNumber

            'Me.txtAdjBy.Text = Security.GetCurrentUser.Name

            

            UpdateData(False)

            Me.Header1.NavigationBar.Add("Back to Order List", Me.ReturnURL)
            Me.Header1.MenuIndex = EMenuIndex.InternalOrderList
        End If
    End Sub

    Private Sub SaveData()
        UpdateData(True)
        Try
            PageBO.Save()
            Response.Redirect(Me.ReturnURL)
            '            Me.lblStatus.Text = Me.SAVE_SUCCESS_TEXT
        Catch ex As Exception
            Throw New ApplicationException("Error occurs when saving", ex)
        End Try
    End Sub

    Private Sub ddlProductInfo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        UpdateData(False)
    End Sub

    Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
        UpdateData(False)
    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        SaveData()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Response.Redirect(Me.ReturnURL)
    End Sub

    'Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Me.SaveData()
    '    Me.ddlProductInfo.SelectedIndex -= 1
    '    UpdateData(False)
    'End Sub

    'Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Me.SaveData()
    '    Me.ddlProductInfo.SelectedIndex += 1
    '    UpdateData(False)
    'End Sub
End Class
